package com.blog.blog.util.aop;

import com.blog.blog.util.annotations.RequirePerm;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class RequirePermAspect {

    private final HttpServletRequest request;
    private final StringRedisTemplate stringRedisTemplate;
    private final com.blog.blog.mapper.UserMapper userMapper;

    public RequirePermAspect(HttpServletRequest request, StringRedisTemplate stringRedisTemplate, com.blog.blog.mapper.UserMapper userMapper) {
        this.request = request;
        this.stringRedisTemplate = stringRedisTemplate;
        this.userMapper = userMapper;
    }

    @Around("@annotation(requirePerm)")
    public Object checkPerm(ProceedingJoinPoint pjp, RequirePerm requirePerm) throws Throwable {
        String auth = request.getHeader("Authorization");
        if (auth == null || !auth.startsWith("Bearer ")) {
            throw new IllegalArgumentException("未授权");
        }
        String token = auth.substring(7);
        String v = stringRedisTemplate.opsForValue().get("auth:token:" + token);
        if (v == null) {
            throw new IllegalArgumentException("未授权");
        }
        // v 格式：userId|roles
        String[] arr = v.split("\\|");
        Long userId = Long.parseLong(arr[0]);
        String roles = arr.length > 1 ? arr[1] : "";
        if (roles != null && roles.contains("ADMIN")) {
            return pjp.proceed();
        }
        // 加载权限集合并匹配注解要求
        String perms = userMapper.selectPermsByUserId(userId);
        java.util.Set<String> have = new java.util.HashSet<>();
        if (perms != null && !perms.isBlank()) {
            for (String s : perms.split(",")) have.add(s.trim());
        }
        for (String need : requirePerm.value()) {
            if (!have.contains(need)) {
                throw new IllegalArgumentException("无权限: " + need);
            }
        }
        return pjp.proceed();
    }
}


